import React from 'react';
import { observer } from 'mobx-react';
import { Input } from 'antd';
import jQuery from 'jquery';
import { formatFloatValue } from '../../../util/modeUtil';

interface Props {
    editable?: boolean;
    value?: string;
    defaultValue?: string;
    onChange?: (value) => void;
    onBlur?: () => void;
    detailtype: string;
    reg: RegExp;
    disabled?:boolean;
    column?;
    row?;
    qfws?;
    max?;
    min?;
}
export class IntegerInput extends React.Component<Props, any> {
    constructor(props: Props) {
        super(props);
    }
    formatter = (fieldhtmltype,fieldtype,val?: string | number) => {
        const { qfws = 2  } = this.props;
        let _value = val ? `${val}` : ``;
        if (_value.endsWith(".")) {
            _value += "0";
        }
        _value = jQuery.trim(_value).length > 0 ? _value.replace(/\,/g, '') : '';
        if(fieldhtmltype=='1'&&fieldtype=='5'){
            return formatFloatValue(_value, qfws, true);
        }else{
            return formatFloatValue(_value, qfws, false);
        }
    }
    onChange = (e) => {
        const { value } = e.target;
        const { reg,max,min } = this.props;
        if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
            const intValue = (value === '' || value === '-') ? value : value;
            if(max&&intValue>max||min&&intValue<min)return;
            this.props.onChange && this.props.onChange(intValue);
        }
    }
    onBlur = (e) => {
       const { value } = e.target;
        const { reg,column,row } = this.props;
        const {fieldhtmltype,fieldtype}=column;
        if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
            let intValue = (value === '' || value === '-') ? value : value;
            intValue = this.formatter(fieldhtmltype,fieldtype,intValue);
            this.props.onChange && this.props.onChange(intValue);
            column.onChange&&column.onChange(intValue,row);
        }
    }
    onFocus = (e) => {
        const {value} = e.target;
        if (value.indexOf(",") === -1) {
            return;
        }
        const {column, row} = this.props;
        let intValue = jQuery.trim(value).length > 0 ? value.replace(/\,/g, '') : '';
        this.props.onChange && this.props.onChange(intValue);
        column.onChange && column.onChange(value, row);
    }


    render() {
        const {column,row}=this.props;
        return <div >
            <Input
                {...this.props}
                disabled={this.props.disabled}
                value={this.props.value}
                onBlur={e=>this.onBlur(e)}
                onFocus={e=>this.onFocus(e)}
                onChange={e=>{this.onChange(e);column.onChange&&column.onChange(e.target.value,row)}}
            />
            </div>
    }
}

export default observer((props: Props) => {
    return (
        props.editable ? <IntegerInput {...props} /> : <span>{props.value}</span>
    )
});
